package com.ruoyi.web.controller.main;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.system.domain.*;
import com.ruoyi.system.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 医保基金-报销申请Controller
 * 
 * @author ruoyi
 * @date 2025-04-13
 */
@Api("医保基金-报销申请")
@RestController
@RequestMapping("/system/reimbursementApplication")
public class ReimbursementApplicationController extends BaseController
{
    @Autowired
    private IReimbursementApplicationService reimbursementApplicationService;

    @Autowired
    private IInsuredPersonsService insuredPersonsService;

    @Autowired
    private IFinanceDepartInfoService financeDepartInfoService;

    @Autowired
    private ITransactionRecordService transactionRecordService;

    @Autowired
    private IReimbursementRecordsService reimbursementRecordsService;



    /**
     * 报销申请-转账
     */
    @Log(title = "医保基金-报销申请", businessType = BusinessType.UPDATE)
    @PostMapping("/transfer")
    @ApiOperation("报销申请-转账")
    public AjaxResult transferMoney(@RequestBody ReimbursementApplicationParam param)
    {
        ReimbursementApplication reimbursementApplication = reimbursementApplicationService.selectReimbursementApplicationById(param.getId());
        if(ObjectUtils.isNotEmpty(reimbursementApplication)){
            // todo 扣减 医保局账户的钱
            FinanceDepartInfo financeDepartInfo = financeDepartInfoService.selectFinanceDepartInfoById(1L);
            financeDepartInfo.setBalance(financeDepartInfo.getBalance().subtract(reimbursementApplication.getReimbursementAmount()));
            financeDepartInfoService.updateFinanceDepartInfo(financeDepartInfo);
            // todo 添加医保局交易记录
            TransactionRecord transactionRecord = new TransactionRecord();
            transactionRecord.setMoney(reimbursementApplication.getReimbursementAmount());
            transactionRecord.setRemark(param.getRemark());
            transactionRecord.setType(0L);
            transactionRecord.setTradingTime(new Date());
            transactionRecord.setUserId(reimbursementApplication.getInsuredPerson());
            transactionRecordService.insertTransactionRecord(transactionRecord);
            // todo 添加 参保人员账户的钱
            InsuredPersons insuredPersons = insuredPersonsService.selectInsuredPersonsById(reimbursementApplication.getInsuredPerson());
            if(param.getAccountType() == 0){// 个人账户
                insuredPersons.setPersonalBalance(insuredPersons.getPersonalBalance().add(reimbursementApplication.getReimbursementAmount()));
            }else if (param.getAccountType() == 1){
                insuredPersons.setFundBalance(insuredPersons.getPersonalBalance().add(reimbursementApplication.getReimbursementAmount()));
            }
            insuredPersonsService.updateInsuredPersons(insuredPersons);
            // todo 添加 参保人员报销记录
            ReimbursementRecords reimbursementRecords = new ReimbursementRecords();
            reimbursementRecords.setReimbursementAmount(reimbursementApplication.getReimbursementAmount());
            reimbursementRecords.setStatus(0L);
            reimbursementRecords.setMedicalInstitution(reimbursementApplication.getMedicalInstitution());
            reimbursementRecords.setSelfPayment(BigDecimal.ZERO);
            if(param.getAccountType() == 0){// 个人账户
                reimbursementRecords.setTransferAccount(insuredPersons.getPersonalCode());
            }else if (param.getAccountType() == 1){
                reimbursementRecords.setTransferAccount(insuredPersons.getFundCode());
            }
            reimbursementRecords.setVisitDate(reimbursementApplication.getApprovalTime());
            reimbursementRecords.setInsuredPersonD(reimbursementApplication.getInsuredPerson());
            reimbursementRecords.setTotalMedicalCost(reimbursementApplication.getReimbursementAmount());
            reimbursementRecordsService.insertReimbursementRecords(reimbursementRecords);

            reimbursementApplication.setStatus(1L);
            reimbursementApplicationService.updateReimbursementApplication(reimbursementApplication);
            return success("转账成功");
        }
        return error("参数缺失id");
    }

    /**
     * 查询医保基金-报销申请列表
     */
//    @PreAuthorize("@ss.hasPermi('system:application:list')")
    @GetMapping("/list")
    @ApiOperation("查询医保基金-报销申请列表")
    public TableDataInfo list(ReimbursementApplication reimbursementApplication)
    {
        startPage();
        List<ReimbursementApplication> list = reimbursementApplicationService.selectReimbursementApplicationList(reimbursementApplication);
        if(CollectionUtils.isNotEmpty(list)){
            list = list.stream().peek(item -> {
                InsuredPersons insuredPersons = insuredPersonsService.selectInsuredPersonsById(item.getInsuredPerson());
                if(ObjectUtils.isNotEmpty(insuredPersons)){
                    item.setInsuredPersons(insuredPersons);
                }
            }).collect(Collectors.toList());
        }
        return getDataTable(list);
    }


    /**
     * 获取医保基金-报销申请详细信息
     */
//    @PreAuthorize("@ss.hasPermi('system:application:query')")
    @GetMapping(value = "/{id}")
    @ApiOperation("获取医保基金-报销申请详细信息")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(reimbursementApplicationService.selectReimbursementApplicationById(id));
    }

    /**
     * 新增医保基金-报销申请
     */
//    @PreAuthorize("@ss.hasPermi('system:application:add')")
    @Log(title = "医保基金-报销申请", businessType = BusinessType.INSERT)
    @PostMapping
    @ApiOperation("新增医保基金-报销申请")
    public AjaxResult add(@RequestBody ReimbursementApplication reimbursementApplication)
    {
        return toAjax(reimbursementApplicationService.insertReimbursementApplication(reimbursementApplication));
    }

    /**
     * 修改医保基金-报销申请
     */
//    @PreAuthorize("@ss.hasPermi('system:application:edit')")
    @Log(title = "医保基金-报销申请", businessType = BusinessType.UPDATE)
    @PutMapping
    @ApiOperation("修改医保基金-报销申请")
    public AjaxResult edit(@RequestBody ReimbursementApplication reimbursementApplication)
    {
        return toAjax(reimbursementApplicationService.updateReimbursementApplication(reimbursementApplication));
    }

    /**
     * 删除医保基金-报销申请
     */
//    @PreAuthorize("@ss.hasPermi('system:application:remove')")
    @Log(title = "医保基金-报销申请", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    @ApiOperation("删除医保基金-报销申请")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(reimbursementApplicationService.deleteReimbursementApplicationByIds(ids));
    }
}
